package table.models;

import java.awt.Component;

import javax.swing.BorderFactory;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.border.Border;
import javax.swing.table.DefaultTableCellRenderer;

import com.sun.org.apache.xpath.internal.functions.WrongNumberArgsException;

import core.ColorConstants;
import db.newversion.ColorDB;

public class ParticipantsTableModelRenderer extends DefaultTableCellRenderer {

	@Override
	public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
		JComponent toReturn;

		if (value == null) {
			return null;
		}

		if (value.toString().equals("true") || value.toString().equals("false")) {
			// Checkbox erzeugen
			toReturn = new JCheckBox();
			((JCheckBox) toReturn).setSelected(value.toString().equals("true"));
			((JCheckBox) toReturn).setHorizontalAlignment(CENTER);

		} else {
			// Label erzeugen
			toReturn = new JLabel(value.toString());
		}

		toReturn.setOpaque(true);
		Border b = BorderFactory.createEmptyBorder(1, 1, 1, 1);
		toReturn.setBorder(b);
		toReturn.setFont(table.getFont());
		toReturn.setForeground(table.getForeground());
		toReturn.setBackground(table.getBackground());

		// Angezeigte Zeile in ModellZeile umwandeln
		row = table.convertRowIndexToModel(row);

		String ageClass = table.getModel().getValueAt(row, ((ParticipantsTableModel) table.getModel()).getAgeClassColumnIndex()).toString();
		String bowCathegory = table.getModel().getValueAt(row, ((ParticipantsTableModel) table.getModel()).getCathegoryColumnIndex()).toString();
		String gender = table.getModel().getValueAt(row, ((ParticipantsTableModel) table.getModel()).getGenderColumnIndex()).toString();
		try {
			toReturn.setBackground(ColorDB.getInstance().getElement(bowCathegory, ageClass, gender));
		} catch (WrongNumberArgsException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		if (hasFocus) {
			toReturn.setForeground(ColorConstants.HASFOCUS_FOREGROUND);
			toReturn.setBackground(ColorConstants.HASFOCUS_BACKGROUND);
		} else if (isSelected) {
			toReturn.setForeground(ColorConstants.SELECTED_FOREGROUND);
			toReturn.setBackground(ColorConstants.SELECTED_BACKGROUND);
		}
		return toReturn;
	}
}
